﻿using System;
using System.ComponentModel;
using System.Linq;
using Inaction.Core;
using Inaction.Mapping;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;

namespace Inaction.Business.Security
{
    [Table("MenuInfo"), DisplayName("菜单"), Serializable]
    public class MenuInfo : Abstract.MenuInfo<MenuInfo>
    {
        #region 子表

        [Display(Description = "子菜单"), DisplayName("子菜单")]
        public MenuInfoList SubMenus
        {
            get { return GetChild<MenuInfoList, MenuInfo>(); }
        }

        [Display(Description = "菜单角色"), DisplayName("菜单角色")]
        public MenuRoleList MenuRoles
        {
            get { return GetChild<MenuRoleList, MenuRole>(); }
        }

        public MenuRoleVList MenuRoleViews
        {
            get { return GetChild<MenuRoleVList, MenuRoleV>(); }
        }
        #endregion

        static MenuInfo()
        {
            AddChildRelationship<MenuInfo>(ParentIdProperty);
            OnQueryingEvent += MenuInfo_OnQueryingEvent;
        }

        static System.Collections.Generic.List<MenuInfo> MenuInfo_OnQueryingEvent(SqlStatement sql, ref bool skiped)
        {
            if (!sql.ParaValues.Any(p => p.Name.Equals(MenuInfo.AppTypeProperty.Column.ParameterName, StringComparison.OrdinalIgnoreCase)))
            {
                sql.AddWhereClause(new KeyValuePair<IProperty, object>(MenuInfo.AppTypeProperty,
#if WINDOWS
 Inaction.AppType.WinForm
#elif WPF
                Inaction.AppType.WPF
#elif WEB 
                Inaction.AppType.Web
#endif
));
            }
            skiped = false;
            return null;
        }

        public void RefreshMenuRole(RoleInfo role)
        {
            var menuRole = MenuRoles.FirstOrDefault(p => p.RoleId == role.Id);
            if (menuRole != null && !role.Selected)
            {
                MenuRoles.Remove(menuRole);
            }
            if (menuRole == null && role.Selected)
            {
                menuRole = MenuRoles.AddNew();
                menuRole.RoleId = role.Id;
            }
        }
    }

    [DisplayName("菜单列表"), Serializable]
    public class MenuInfoList : Inaction.Business.EntityList<MenuInfoList, MenuInfo>
    {
    }
}
